/*
 * =============================================================================
 * "THE BEER-WARE LICENSE" (Revision 42):
 * <eirikb@google.com> wrote this file. As long as you retain this notice you
 * can do whatever you want with this stuff. If we meet some day, and you think
 * this stuff is worth it, you can buy me a beer in return Eirik Brandtzæg
 * =============================================================================
 */
package no.eirikb.robotec.terminal.element;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import no.eirikb.robotec.telnet.TelnetCommands;
import no.eirikb.robotec.terminal.Terminal;

/**
 *
 * @author eirikb
 * @author <a href="mailto:eirikb@google.com">eirikb@google.com</a>
 */
public class CommandBox extends Command {

    private int cX;  // Cursor X
    private List<String> lines;
    public CommandBox(Terminal terminal, int x, int y, int width, int height) {
        super(terminal, x, y, width, height);
        cX = 0;
        lines = new ArrayList<String>();
    }

    @Override
    public void read(int c) {
        if (c != 13) {
            if (++cX < getWidth()) {
                setReadLine(getReadLine() + (char)c);
                lines.set(lines.size() - 1, lines.get(lines.size() - 1) + (char) c);
                if (isEcho()) {
                    try {
                        getTerminal().getServer().getSocket().getOutputStream().write(c);
                    } catch (IOException ex) {
                        Logger.getLogger(Terminal.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        } else {
            readLine(getReadLine());
            setReadLine("");
            cX = 0;
        }
    }

    @Override
    public void sendLine(String line) {
        if (line.length() > getWidth()) {
            line = line.substring(0, getWidth());
        }
        if (lines.size() >= getHeight()) {
            for (int i = 0; i < lines.size() - 1; i++) {
                lines.set(i, lines.get(i + 1));
            }
            lines.remove(lines.size() - 1);
            String moveUp = TelnetCommands.CLEARRECT(getX(), getY(), getWidth(), getHeight());
            for (int i = 0; i < lines.size(); i++) {
                moveUp += TelnetCommands.MOVECURSOR(getX(), getY() + i + 1) + lines.get(i);
            }
            getTerminal().getServer().sendText(moveUp);
        }
        lines.add(line);
        getTerminal().getServer().sendLagText(TelnetCommands.MOVECURSOR(getX(), getY() + lines.size()) + line);
    }
}
